﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace CalcEng
{
    public class BlockNew
    {
        public static void WriteToBlocks(string blockName, string tdwPath, List<CalcResult> cRets)
        {
            List<string> codes = new List<string>();
            foreach (CalcResult cre in cRets)
            {
                if(cre.iav > 0.56F && cre.jav > 1.2F)
                {
                    if (cre.iav > 0.77F && cre.jav > 1.48F)
                    {
                        codes.Add(cre.code);
                    }
                    else if ( cre.jav > 1.68F)
                    {
                        codes.Add(cre.code);
                    }
                    else if (cre.mav > 2.8F)
                    {
                        codes.Add(cre.code);
                    }
                }
            }

            if (codes.Count() > 0)
            {
                string blkCfgFile = tdwPath + @"\T0002\blocknew\blocknew.cfg";
                FileStream fs = new FileStream(blkCfgFile, FileMode.Open, FileAccess.Write, FileShare.Read);
                byte[] bytearr = new byte[blockName.Length];
                char[] charr = blockName.ToCharArray();
                for (int i = 0; i < charr.Length; i++)
                {
                    bytearr[i] = (byte)charr[i];
                }

                fs.Seek(0, SeekOrigin.End);
                fs.Write(bytearr, 0, bytearr.Length);
                for (int i = bytearr.Length; i < 0x32; i++)
                {
                    fs.WriteByte(0);
                }
                fs.Write(bytearr, 0, bytearr.Length);
                for (int i = bytearr.Length; i < 0x46; i++)
                {
                    fs.WriteByte(0);
                }
                fs.Flush();
                fs.Close();

                string blkListFile = tdwPath + @"\T0002\blocknew\" + blockName + @".blk";
                fs = new FileStream(blkListFile, FileMode.OpenOrCreate, FileAccess.Write);
                bytearr = new byte[9];
                bytearr[0] = 0x0d;
                bytearr[1] = 0x0a;
                bytearr[2] = (byte)'0';
                foreach (string code in codes)
                {
                    string str = code.PadLeft(6, '0');
                    char[] chararr = str.ToCharArray();
                    for (int i = 0; i < 6; i++)
                    {
                        bytearr[3 + i] = (byte)chararr[i];
                    }
                    fs.Write(bytearr, 0, 9);
                }
                fs.Flush();
                fs.Close();
            }
        }
    }
}
